package risoe.syslab.fhnew.controller.plugin;

/*
 * Copyright (c) 2012-2014, Technical University of Denmark (DTU)
 * All rights reserved.
 * 
 * The Flexhouse 2.0 platform ("this software") is licensed under the
 * BSD 3-clause license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   - Neither the name of DTU nor the names of its contributors may be used to
 *     endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE TECHNICAL UNIVERSITY OF DENMARK BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import risoe.syslab.fhnew.common.SystemConstants.DeviceType;
import risoe.syslab.fhnew.config.ActuatorConfig;
import risoe.syslab.fhnew.config.BuildingConfig;
import risoe.syslab.fhnew.config.RoomConfig;
import risoe.syslab.fhnew.controller.ControllerConfig;
import risoe.syslab.fhnew.controller.PluginController;
import risoe.syslab.fhnew.hw.Actuator;
import risoe.syslab.fhnew.hw.Sensor;
import risoe.syslab.model.CompositeMeasurement;

/**
 * PluginController for doing PRBS tests in powerflexhouse 3
 * @author M. Svendsen
 */
public class ThermodynamicMeasurementController extends PluginController {
	// Constants
	public static final String NAME = "ThermoDynamicMeasurementController";
	public final static String OWNER = "masv";
	public static final int MINUTE_IN_MILLIS = 60000;

	// Reference to get house data
	private BuildingConfig mBuildingConfig;

	// Data
	public ArrayList<Float> mList;
	private int mIndex = 0;

	// For keeping track of time
	private ScheduledExecutorService mExecutor;
	private Runnable mTask;

	public static void main(String[] args) {
		try {
			String configFile = args.length > 0? args[0]: null;
			new ThermodynamicMeasurementController(NAME, OWNER, configFile);
		} catch (RemoteException e) {
			// RMI Connection was unsuccessful 
			System.out.println("RMI Error: "+e.getMessage());
			System.exit(0);
		} catch (InstantiationException e) {
			// Controller name was already taken, or one of the requested permissions was already used by
			// another plugincontroller
			System.out.println("Argument Error: "+e.getMessage());
			System.exit(0);
		}
	}

	public ThermodynamicMeasurementController(String name, String owner, String cfgfile)
			throws RemoteException, InstantiationException {
		super(name, owner, cfgfile);
	}

	@Override
	public ControllerConfig supplyControllerConfig(ControllerConfig config) {
		// We are controller heater states
		config.addControlledDeviceType(DeviceType.PowerControlledHeater);

		// We want to log temperatures
		config.addTypeSubscription(DeviceType.Temperature);
		return config;
	}

	@Override
	public void initialStateReceived(Actuator[] actuators) {
		// Turn of all heaters, then initialize controller
		for (Actuator actuator : actuators){
			if (actuator.getType() == DeviceType.PowerControlledHeater){
				setActuator(actuator.getName(), new CompositeMeasurement(0.0));
			}
		}

		mExecutor = Executors.newSingleThreadScheduledExecutor();
		mTask = new Runnable() {
			@Override
			public void run() {
				if (mList.size() <= mIndex){

					// All done!
					mExecutor.shutdown();
					log("END", "THERMODYNAMIC MEASUREMENT COMPLETED");
					System.exit(0);
					return;
				}

				Float state = mList.get(mIndex++);
				if (state != null){
					for (ActuatorConfig actuator : mBuildingConfig.getAllActuators()){
						if (actuator.getType() == DeviceType.PowerControlledHeater){
							RoomConfig room = mBuildingConfig.getRoomForActuator(actuator.getName());
							if (room != null){
								String roomName = room.getRoomName();
								if (roomName.equals("Bathroom") || roomName.equals("Basement_Room") ||
										roomName.equals("Toilet")){
									setActuator(actuator.getName(), new CompositeMeasurement(state.floatValue()));
									System.out.println("Set actuator"+actuator.getName()+"to: "+state.floatValue());
								}
							}
						}
					}
				}
			}
		};
		mList = new ArrayList<Float>();

		mBuildingConfig = getBuildingConfig();

		// Load the info into list
		FileReader fr;
		try {
			fr = new FileReader("conf/PRBS1.txt");
			BufferedReader br = new BufferedReader(fr);

			String read = br.readLine();
			while (read != null){
				mList.add(Float.valueOf(read));

				// read the next line
				read = br.readLine();
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Start the controller!
		log("INIT", "THERMODYNAMIC MEASUREMENT STARTED");
		mExecutor.scheduleWithFixedDelay(mTask, 0, 1, TimeUnit.MINUTES);
	}

	@Override
	public void sensorUpdated(Sensor s) {
		// Log temperature
		log(s.getName(), String.valueOf(s.getValue().value));
	}
}
